#include "RingQueue.hpp"
#include "Task.hpp"
#include <ctime>

void *Consumer(void *agrs)
{
    RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(agrs);
    while (1)
    {
        sleep(1);
        // 消费
        Task t;
        rq->Pop(&t);

        // 处理数据
        std::cout << "Consumer -> " << t.result() << std::endl;
    }
    return nullptr;
}
void *Productor(void *agrs)
{
    RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(agrs);

    while (1)
    {
        // 构建数据
        int x = rand() % 10 + 1; // [1, 10]
        usleep(x * 1000);
        int y = rand() % 10 + 1; // [1, 10];
        Task t(x, y);

        // 生产数据
        rq->Push(t);
        std::cout << "Productor-> " << t.debug() << std::endl;
    }
    return nullptr;
}

int main()
{
    srand(time(nullptr) ^ getpid());
    RingQueue<Task> *rq = new RingQueue<Task>(5);

    pthread_t c1, c2, p1, p2, p3;
    pthread_create(&c1, nullptr, Consumer, rq);
    pthread_create(&c2, nullptr, Consumer, rq);
    pthread_create(&p1, nullptr, Productor, rq);
    pthread_create(&p2, nullptr, Productor, rq);
    pthread_create(&p3, nullptr, Productor, rq);

    pthread_join(c1, nullptr);
    pthread_join(c2, nullptr);
    pthread_join(p1, nullptr);
    pthread_join(p2, nullptr);
    pthread_join(p3, nullptr);

    return 0;
}